package com.thz.houserental.infrastructure.web.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.thz.houserental.infrastructure.advice.log.Log;
import com.thz.houserental.infrastructure.exception.ParameterException;
import com.thz.houserental.infrastructure.log.BusinessType;
import com.thz.houserental.infrastructure.table.Dict;
import com.thz.houserental.infrastructure.table.DictData;
import com.thz.houserental.infrastructure.web.dto.DictDataDto;
import com.thz.houserental.infrastructure.web.dto.DictDto;
import com.thz.houserental.infrastructure.web.dto.DictRequest;
import com.thz.houserental.infrastructure.web.service.DictDataService;
import com.thz.houserental.infrastructure.web.service.DictService;
import com.thz.houserental.infrastructure.web.vo.DictDataInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

@RestController
@RequestMapping("/dict")
@Tag(name = "字典管理")
public class DictController {
    private final DictService dictService;
    private final DictDataService dictDataService;

    public DictController(DictService dictService, DictDataService dictDataService) {
        this.dictService = dictService;
        this.dictDataService = dictDataService;
    }

    @PostMapping("/queryPage")
    @Operation(summary = "字典管理分页查询")
    @Log(title = "字典模块管理", businessType = BusinessType.OTHER)
    public IPage<Dict> queryDictPage(@RequestBody DictRequest request) {
        IPage<Dict> queryPage = dictService.queryPage(request);
        return queryPage;
    }

    @PostMapping("/add")
    @Operation(summary = "字典管理新增")
    @Log(title = "字典模块管理", businessType = BusinessType.INSERT)
    public void addDictCode(@RequestBody DictDto dictDto) {
        if (StringUtils.hasText(dictDto.getDictCode())) {
            boolean exist = dictService.checkDictExistByDictCode(dictDto.getDictCode());
            if (exist) throw new ParameterException(10501);
        }
        Dict dict = new Dict();
        BeanUtils.copyProperties(dictDto, dict);
        dictService.save(dict);
    }

    @DeleteMapping("/{dictId}")
    @Operation(summary = "字典管理根据id删除")
    @Log(title = "字典模块管理", businessType = BusinessType.DELETE)
    public void deleteByDictId(@PathVariable String dictId) {
        boolean exist = dictService.checkDictExistByDictId(dictId);
        if (!exist) throw new ParameterException(10502);
        dictService.removeById(dictId);
    }

    @PutMapping("/{dictId}")
    @Operation(summary = "字典管理根据id进行跟新")
    @Log(title = "字典模块管理", businessType = BusinessType.UPDATE)
    public void updateByDictId(@PathVariable String dictId,
                                 @RequestBody Dict dictDto) {
        boolean exist = dictService.checkDictExistByDictId(dictId);
        if (!exist) throw new ParameterException(10502);
        
        dictDto.setId(dictId);
        dictService.updateById(dictDto);
    }

    @Operation(summary = "新增字典数据")
    @PostMapping("/data/add")
    @Log(title = "字典数据管理模块", businessType = BusinessType.INSERT)
    public void addDictData(@RequestBody @Valid DictDataDto dictDataDto) {
        if (StrUtil.isNotEmpty(dictDataDto.getDictCode())) {
            dictDataService.checkByCodeAndKey(dictDataDto.getDictCode(), dictDataDto.getDictKey());
        }
        DictData dictData = new DictData();
        BeanUtils.copyProperties(dictDataDto, dictData);
        dictDataService.save(dictData);
    }
    
    @Operation(summary = "获取字典配置详情")
    @GetMapping("/{dictId}")
    public DictDataInfo getDictDataInfo(@PathVariable String dictId) {
        boolean exist = dictService.checkDictExistByDictId(dictId);
        if(!exist) {
            throw new ParameterException(10502);
        }
        return this.dictDataService.getDictDataInfo(dictId);
    }
    
    @Operation(summary = "更新字典数据")
    @PutMapping("/data/{dictId}")
    public void updateDictData(@RequestBody @NotNull List<DictData> dictDataList, @PathVariable String dictId) {
        boolean exist = dictService.checkDictExistByDictId(dictId);
        if(!exist) {
            throw new ParameterException(10502);
        }
        //重置dictId， 使用自定义id
        dictDataList.forEach(e -> {
            e.setId(null);
        });
        Dict dict = this.dictService.getById(dictId);
        dictDataList.forEach(e -> {
            e.setDictCode(dict.getDictCode());
        });
        QueryWrapper<DictData> qu = new QueryWrapper<DictData>()
                .eq("dict_code", dict.getDictCode());
        
        this.dictDataService.remove(qu);
        dictDataService.saveBatch(dictDataList);
    }
}
